// 刷新页面 回到顶部
window.onbeforeunload = function () {
  window.scrollTo(0, 0);
}


// 根据本地uid 判断页面的显示隐藏
let Yongh = document.querySelector(".Yongh")
let Dengl = document.querySelector(".Dengl")
let MyxxNoid = document.querySelector(".MyXX_Noid")
let MyxxId = document.querySelector(".MyXX_id")
if (!localStorage.getItem("uid")) {
  console.log(0);
  Yongh.style.display = "none"
  Dengl.style.display = "block"
  MyxxNoid.style.display = "block"
  MyxxId.style.display = "none"
} else {
  Yongh.style.display = "block"
  Dengl.style.display = "none"
  MyxxNoid.style.display = "none"
  MyxxId.style.display = "block"
}

layui.use(function () {
  var carousel = layui.carousel;
  // 渲染 - 图片轮播
  carousel.render({
    elem: '#ID-carousel-demo-image',
    width: '546px',
    height: '315px',
    interval: 2000
  });
});
// 点击退出账号
function bakeHander() {
  localStorage.removeItem('uid');
  location.reload();
}

// 点击跳转购物车
function GoHander() {
  console.log("点击了");
  //检查本地存储是否存在uid
  if (localStorage.getItem('uid')) {

    window.location.href = "./05-购物车.html"
  } else {
    layui.use(function () {
      layui.layer.msg("没登录")
    })
  }
}


// 页面划过样式
let Hleft = document.querySelector(".h_left li") //ul外层
let QqList = document.querySelector(".Quanq ul") //ul本人
let MyXin = document.querySelector(".My_Xin") //个人信息

// 全球位置
Hleft.addEventListener("mouseenter", function () {
  QqList.style.display = "block"
  // console.log("全球位置进入");
})
Hleft.addEventListener("mouseleave", function () {
  QqList.style.display = "none"
  // console.log("全球位置移出");
})

/* 
  mouseenter鼠标进入（实用）
  mouseleave鼠标移出

  mouseover鼠标进入（垃圾 会冒泡 向子元素）
  mouseout鼠标移出
*/

// 个人信息
Yongh.addEventListener("mouseenter", function () {
  // console.log("个人信息进入");
  MyXin.style.display = "block"
})
Yongh.addEventListener("mouseleave", function () {
  MyXin.style.display = "none"
  // console.log("个人信息移出");
})



// 获取商品列表
let data = {
  pagenum: 1,
  pagesize: 27
}
axiosGet("/api/front/articles", data,).then((r) => {
  console.log(r.data.data);
  // console.log(r);
  let liArr = r.data.data.map(v => `
    <a href="04-详情.html?pid=${v._id}">
      <div class="ShangPin">
        <div class="boxImg">
          <img src="${v.pict_url}" alt="">
        </div>
        <div class="boxTxt">
          <div class="title1">${v.title}</div>
          <div class="title2">
            <div style="display:${v.icons ? "" : "none"}">${v.icons ? v.icons[0].text : ""}</div>
            <div style="display:${v.icons ? v.icons.length == 2 ? "" : "none" : "none"}">${v.icons ? v.icons.length == 2 ? v.icons[1].text : "" : ""}</div>
          </div>
          <div class="title3">￥${v.real_wap_price}</div>
        </div>
      </div>
    </a>
  `);
  document.querySelector(".main_ShangPin").innerHTML = liArr.join("")
})



// 显示回到顶部
document.addEventListener("scroll", function () {
  var scrollTop = document.documentElement.scrollTop;
  var addBox = document.querySelector('.add_box');
  if (scrollTop >= 652) {
    addBox.style.display = "block"
  } else {
    addBox.style.display = "none"
  }
})

// 点击回到顶部
var addBox = document.querySelector('.add_box');
addBox.addEventListener("click", function () {
  console.log("点击");
  animate(window, 0)
})


// 动画效果
function animate(obj, target, callback) {
  clearInterval(obj.timer);
  obj.timer = setInterval(function () {
    var step = (target - window.pageYOffset) / 10;
    step = step > 0 ? Math.ceil(step) : Math.floor(step);
    if (window.pageYOffset == target) {
      clearInterval(obj.timer);

      callback && callback();
    }
    window.scroll(0, window.pageYOffset + step);
  }, 15);
}

// 设置通栏下方的样式
document.addEventListener("scroll", function () {
  let scrollTop = document.documentElement.scrollTop;
  let bigIptMain = document.querySelector(".bigIpt_main") //改变背景色
  let imgBox = document.querySelector('.TB_img img') //改变log大小
  let ErvmaImg = document.querySelector('.Ervma_img')//右方二维码消失

  // console.log(scrollTop);
  if (scrollTop >= 76) {
    bigIptMain.style.backgroundColor = "#fff"
    imgBox.style.width = "80px"
    imgBox.style.marginTop = "10px"
    // ErvmaImg.style.display = "none"
    ErvmaImg.style.visibility = "hidden"
  } else {
    bigIptMain.style.backgroundColor = ""
    imgBox.style.width = ""
    imgBox.style.marginTop = ""
    // ErvmaImg.style.display = "block"
    ErvmaImg.style.visibility = "visible"
  }
})

/* 
// 图片懒加载
const imgserver = new IntersectionObserver(callback)
console.log(imgserver);
function callback(e) {
  // console.log("出现触发,消失触发")
  console.log(e);
  e.forEach(item => {
    // 判断是否相交--出现
    if (item.isIntersecting) {
      console.log(item.target.dataset.src)
      setTimeout(() => {
        item.target.src = item.target.dataset.src
        item.target.removeAttribute("data-src")
      }, 2000);
    }
  })
}
document.querySelectorAll("img").forEach(item => {
  imgserver.observe(item)
})
 */

/* window.addEventListener("scroll", function () {
  // 页面滚动高度
  let scrollTop = this.document.body.scrollTop || document.documentElement.scrollTop
  // console.log(scrollTop);
  // 窗口高度
  let H = window.innerHeight
  // console.log(H);
  // 元素的顶部偏移量
  var myElement = document.getElementById("myElement");
  let offsetTop = myElement.getBoundingClientRect().top + scrollTop;
  console.log(offsetTop);
  if (scrollTop + H >= offsetTop) {
    console.log("到底");
  }
}) */

// 防抖操作
function debounce(func, delay) {
  let timeoutId;
  return function () {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(func, delay);
  };
}

// 触底加载操作
window.addEventListener('scroll', debounce(function () {
  var contentElement = document.getElementById('content');
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
  var documentHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); var threshold = 400; // 距离底部多少像素时触发加载操作

  if (scrollTop + windowHeight >= documentHeight - threshold) {
    console.log("触底");
    contentElement.innerHTML += '<p>更多内容...</p>';
    // 加载更多内容的操作
    loadMoreContent();
  }
}, 400)); // 延迟时间为200毫秒

function loadMoreContent() {
  // 发送异步请求，获取更多内容
  // 可以使用Ajax、fetch或其他方式发送后端请求
  // 将返回的内容添加到容器元素中
  let data = {
    pagenum: 1,
    pagesize: 6,
  }
  axiosGet("/api/front/articles", data,).then((r) => {
    console.log(r.data.data);
    console.log(r);
    let liArr = r.data.data.map(v => `
    <a href="04-详情.html?pid=${v._id}">
      <div class="ShangPin">
        <div class="boxImg">
          <img src="${v.pict_url}" alt="">
        </div>
        <div class="boxTxt">
          <div class="title1">${v.title}</div>
          <div class="title2">
            <div>运险费</div>
            <div>满10减200</div>
          </div>
          <div class="title3">￥${v.real_wap_price}</div>
        </div>
      </div>
    </a>
  `);
    document.querySelector("#content").innerHTML = liArr.join("")
  })
}

// 搜索框
let Ipt = document.querySelector("#Ssbox input")
let Btn = document.querySelector("#Ssbox #SouSuo")
let firstLi = document.querySelector("#Ssbox ul li:first-child");
let timerId;

// 点击搜索按钮
Btn.addEventListener("click", searchHandler)

//回车键搜索 
Ipt.addEventListener("keydown", function (event) {
  if (event.key === "Enter") {
    searchHandler();
  }
});

function searchHandler() {
  let placeholderValue = Ipt.getAttribute("placeholder");
  let keyword = encodeURIComponent(Ipt.value);
  console.log(placeholderValue);
  if (Ipt.value === "") {
    let searchUrl = `https://s.taobao.com/search?&q=${placeholderValue}`;
    window.location.href = searchUrl;
  } else {
    let searchUrl = `https://s.taobao.com/search?&q=${keyword}`;
    window.location.href = searchUrl;
  }
}

// 输入框模糊搜索
Ipt.addEventListener("input", debounce(getListHandler, 200))//防抖
function debounce(fn, delay) {
  return function () {
    clearTimeout(timerId);
    timerId = setTimeout(fn, delay);
  };
}
function getListHandler() {
  let oScript = document.createElement("script")
  let keyword = encodeURIComponent(Ipt.value);
  /* let oUl = document.querySelector("#Ssbox ul")
  if (Ipt.value === "") {
    oUl.innerHTML = ""; // 输入框内容为空时，立即清空 ul 元素
    return;
  } */
  oScript.src = `https://suggest.taobao.com/sug?code=utf-8&q=${keyword}&callback=__jp6`;
  document.body.appendChild(oScript)

}

// JSONP响应的函数
function __jp6(data) {
  console.log(data);
  let oUl = document.querySelector("#Ssbox ul")
  let html = ""
  if (!data.result) {
    oUl.innerHTML = ""
    oUl.style.display = "none"
    return
  }
  data.result.forEach((item) => {
    const brand = item[0]; // 去除字符串中的空格
    html += `
    <a href="https://s.taobao.com/search?&q=${brand}">
    <li>${brand}</li>
    </a>`;
  });
  oUl.innerHTML = html;
}





